<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { getDonationTypeAPI } from '@/services/home'
import type { DonationType } from '@/types/home'
import DeviceShelf from './components/device-shelf.vue'
import DonationList from './components/donation-list.vue'
import { onShow, onLoad, onReady } from '@dcloudio/uni-app'

// 当前分类：设备、取货、入库
const currentTab = ref('device')

// 捐赠物类型列表
const donationTypes = ref<DonationType[]>([])

// 状态栏高度
const statusBarHeight = ref(20)
// 导航栏高度
const navBarHeight = 44

// 是否已经初始化完成
const isInitialized = ref(false)

// 跟踪已加载的选项卡
const loadedTabs = ref<Record<string, boolean>>({
  device: false,
  pickup: false,
  storage: false,
})

// 获取系统信息，设置状态栏高度
const getSystemInfo = () => {
  uni.getSystemInfo({
    success: (res) => {
      statusBarHeight.value = res.statusBarHeight || 20
    },
  })
}

// 获取捐赠物种类列表
const fetchDonationTypes = async () => {
  try {
    console.log('获取捐赠物类型数据')
    const res = await getDonationTypeAPI()
    if (res.code === 200 && res.rows) {
      donationTypes.value = res.rows
      console.log('捐赠物类型数据:', donationTypes.value)
    }
  } catch (error) {
    console.error('获取捐赠物类型失败:', error)
  }
}

// 切换标签页
const switchTab = (tab: string) => {
  if (currentTab.value === tab) return

  console.log('切换标签页:', tab)
  currentTab.value = tab

  // 只在首次切换到该标签时加载数据
  if (!loadedTabs.value[tab]) {
    loadComponentData(tab)
    loadedTabs.value[tab] = true
  }
}

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 组件引用
const deviceShelfRef = ref(null)
const pickupListRef = ref(null)
const storageListRef = ref(null)

// 加载指定组件的数据
const loadComponentData = (tab: string) => {
  console.log('加载组件数据:', tab)

  // 延迟一下确保组件已渲染
  setTimeout(() => {
    if (tab === 'device' && deviceShelfRef.value) {
      console.log('加载设备货架数据')
      // @ts-ignore
      deviceShelfRef.value.refreshData && deviceShelfRef.value.refreshData()
    } else if (tab === 'pickup' && pickupListRef.value) {
      console.log('加载取货列表数据')
      // @ts-ignore
      pickupListRef.value.refresh && pickupListRef.value.refresh()
    } else if (tab === 'storage' && storageListRef.value) {
      console.log('加载入库列表数据')
      // @ts-ignore
      storageListRef.value.refresh && storageListRef.value.refresh()
    }
  }, 100)
}

// 初始化第一个标签页的数据
const initFirstTabData = () => {
  if (isInitialized.value) return

  console.log('初始化当前标签页数据:', currentTab.value)
  loadComponentData(currentTab.value)
  loadedTabs.value[currentTab.value] = true
  isInitialized.value = true
}

onLoad((options) => {
  console.log('页面加载 onLoad', options)
  getSystemInfo()
  fetchDonationTypes()
})

onReady(() => {
  console.log('页面就绪 onReady')
  // 页面就绪后初始化当前标签页数据
  nextTick(() => {
    initFirstTabData()
  })
})

onShow(() => {
  console.log('页面显示 onShow')
  // onShow时不再自动刷新数据，依靠用户下拉刷新来更新
})

onMounted(() => {
  console.log('组件挂载 onMounted')
})
</script>

<template>
  <view class="device-pickup">
    <!-- 自定义导航栏 -->
    <view class="custom-nav" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-content">
        <view class="nav-left" @tap="handleBack">
          <view class="back-btn">
            <text class="iconfont icon-arrow-left">←</text>
          </view>
        </view>
        <view class="nav-title">设备取货</view>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 分类标签栏 -->
    <view class="tab-bar">
      <view
        class="tab-item"
        :class="{ active: currentTab === 'device' }"
        @tap="switchTab('device')"
      >
        设备
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'pickup' }"
        @tap="switchTab('pickup')"
      >
        取货
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'storage' }"
        @tap="switchTab('storage')"
      >
        入库
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 设备货架 - 始终渲染，通过v-show控制显示隐藏 -->
      <view v-show="currentTab === 'device'" class="tab-content">
        <device-shelf ref="deviceShelfRef" />
      </view>

      <!-- 取货列表 - type="pickup"对应API type参数为0 -->
      <view v-show="currentTab === 'pickup'" class="tab-content">
        <donation-list ref="pickupListRef" type="pickup" :donation-types="donationTypes" />
      </view>

      <!-- 入库列表 - type="storage"对应API type参数为1 -->
      <view v-show="currentTab === 'storage'" class="tab-content">
        <donation-list ref="storageListRef" type="storage" :donation-types="donationTypes" />
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.device-pickup {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f9fa;
}

// 自定义导航栏
.custom-nav {
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .nav-content {
    display: flex;
    align-items: center;
    height: 44px;
    padding: 0 20rpx;

    .nav-left {
      width: 60rpx;
      display: flex;
      align-items: center;

      .back-btn {
        font-size: 40rpx;
      }
    }

    .nav-title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .nav-right {
      width: 60rpx;
    }
  }
}

// 分类标签栏
.tab-bar {
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);

  .tab-item {
    padding: 20rpx 0;
    margin: 0 30rpx;
    font-size: 30rpx;
    color: #666;
    position: relative;

    &.active {
      color: #2b85e4;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background-color: #2b85e4;
        border-radius: 3rpx;
      }
    }
  }
}

// 内容区域
.content {
  flex: 1;

  .tab-content {
    height: 100%;
    padding-top: 20rpx;
  }
}

// 定义一个简单的箭头图标替代字体图标
.icon-arrow-left {
  display: inline-block;
}
</style>
